package com.publicize.commom.commonutils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

public class FileUtils {
    public static final String  UPLOAD_FOLDER="E:\\前端codes\\htmlAndCss\\毕设\\admin\\images\\headers\\";
    public static final String  UPLOAD_RELATIVE="images\\headers";//相对地址

    public  Result fileUpload(MultipartFile file){
        if (file == null) {
            return Result.ok().data("请选择要上传的图片",201);
        }
        if (file.getSize() > 1024 * 1024 * 10) {
            return Result.ok().data("文件大小不能大于10M",201);
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return Result.ok().data("请选择jpg,jpeg,gif,png格式的图片",201);
        }
        System.out.println(UPLOAD_FOLDER);
        String savePath =UPLOAD_FOLDER;
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        //通过UUID生成唯一文件名
        String filename = UUID.randomUUID().toString().replaceAll("-","") + "." + suffix;
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ok().data("保存文件异常",201);
        }
        return Result.ok().data("filename",filename);
    }
}
